import { useRef, useEffect, useState, useMemo } from "react";
import * as echarts from 'echarts';
import { request } from "../../utils";
import { Cascader } from 'antd-mobile'

function Test() {
  const [data, setData] = useState([]);
  const [date, setDate] = useState(new Date().getFullYear()+'年');
  const [params, setParams] = useState({year: new Date().getFullYear()});
  const pieChartRef = useRef();
  const barChartRef = useRef();
  const [datevisible, setDatevisible] = useState(false)
  const options = useMemo(() => {
      const years = Array.from({ length: 10 }, (_, i) => {
        const year = new Date().getFullYear() - 9 + i
        return {
          label: `${year}年`,
          value: year,
          children: []
        }
      })
    
      // 生成月份选项
      years.forEach(yearObj => {
        if(yearObj.value == new Date().getFullYear()){
          const long = new Date().getMonth()+1
          yearObj.children = Array.from({ length: long }, (_, i) => {
            const month = i + 1
            return {
              label: `${month}月`,
              value: month,
              children: []
            }
          })
        }
        else{
          yearObj.children = Array.from({ length: 12 }, (_, i) => {
          const month = i + 1
          return {
            label: `${month}月`,
            value: month,
            children: []
          }
        })
      }
      })
    
      // 生成日期选项（动态计算天数）
      years.forEach(yearObj => {
        yearObj.children.forEach(monthObj => {
          if(monthObj.value == new Date().getMonth()+1 && yearObj.value == new Date().getFullYear()){
            monthObj.children = Array.from({ length: new Date().getDate() }, (_, i) => ({
              label: `${i + 1}日`,
              value: i + 1
            }))
          }else
          {const daysInMonth = new Date(yearObj.value, monthObj.value, 0).getDate()
          monthObj.children = Array.from({ length: daysInMonth }, (_, i) => ({
            label: `${i + 1}日`,
            value: i + 1
          }))}
        })
      })
    
      return years
    }, [])

  useEffect(() => {
    // 发起请求获取数据
    request.get('/api/auth/bills/all',{params}).then(res => {
      setData(res.data);
    });
  }, [date, params]);

  useEffect(() => {
    if (data.length > 0) {
      // 计算收入与支出比例
      const financeData = data.reduce((acc, item) => {
        const flow = item.bill_type?.flow;
        acc[flow] = (acc[flow] || 0) + parseFloat(item.amount);
        return acc;
      }, { income: 0, outcome: 0 });
      console.log(financeData);

      const pieChartInstance = echarts.init(pieChartRef.current);
      const pieChartOption = {
        title: {
          text: '收入与支出比例',
          left: 'center',
          textStyle: { fontSize: 15, color: '#333',lineHeight: 30, },
        },
        tooltip: { // 添加必要的 tooltip 配置
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['收入', '支出'],
        },
        series: [
          {
            name: '财务数据',
            type: 'pie',
            radius: '50%',
            center: ['50%', '60%'],
            data: [
              { value: financeData.income-financeData.outcome, name: '余额' },
              { value: financeData.outcome, name: '支出' },
            ],
          },
        ],
      };
      pieChartInstance.setOption(pieChartOption);

      // 计算各类型金额分布
      const typeData = data.reduce((acc, item) => {
        const typeName = item.bill_type?.name;
        acc[typeName] = (acc[typeName] || 0) + parseFloat(item.amount);
        return acc;
      }, {});
      console.log(typeData);

      const barChartInstance = echarts.init(barChartRef.current);
      const barChartOption = {
        title: {
          text: '各类型金额分布',
          left: 'center',
          textStyle: { fontSize: 18, color: '#333' },
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
        },
        xAxis: {
          type: 'category',
          data: Object.keys(typeData),
          axisLabel: {
            rotate: 90, // 旋转90度（垂直）
            interval: 0, // 强制显示所有标签
            verticalAlign: 'top', // 垂直对齐方式
            margin: 20, // 标签与轴线的距离
            textStyle: {
              fontSize: 12 // 适当减小字体大小
            }
          },
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            name: '金额',
            type: 'bar',
            data: Object.values(typeData),
            itemStyle: { color: '#5470C6' },
          },
        ],
      };
      barChartInstance.setOption(barChartOption);
    }
  }, [data]);

  return (
    <div style={{ width: '100%', minWidth: '300px' }}>
      <div onClick={() => {setDatevisible(true)}}>{date}</div>
      <div ref={pieChartRef} style={{ width: '100%', height: '180px' }}></div>
      <div ref={barChartRef} style={{ width: '100%', height: '300px' }}></div>
      <Cascader
            options={options}
            visible={datevisible}
            onClose={() => {
              setDatevisible(false)
            }}
            onConfirm={(value) => {
              const[year=null, month=null, date=null] = value
              setParams({year, month, date})
              if(date){



                //
              setDate(year+'年'+'-'+month+'月'+'-'+date+'日')
              }else if(month){
                setDate(year+'年'+'-'+month+'月')
              }else{
                console.log(year+'年')
                setDate(year+'年')
              }}}
          />
    </div>
  );
}

export default Test;